#include "xil_io.h"
#include "iic_slave.h"
//#include "xadc_core.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <ctype.h>
#include <pthread.h>
#include <assert.h>

//#define GPIO_I2C_RESET_ADDR		0x82010000
#define BUFFER_SIZE	32

#ifndef u8
#define u8 unsigned char
#endif

extern unsigned int get_1848_reg(int num,unsigned int offset);

unsigned char SendBuffer[BUFFER_SIZE];

extern unsigned int g_temp[10];
extern unsigned int g_vcc[14];

extern unsigned char srio_stat0;
extern unsigned char srio_stat1;

void xil_setreg32(unsigned int addrBase,unsigned int addrOffset,unsigned int value)
{
	Xil_Out32(addrBase+addrOffset, value);
}

int xil_getreg32(unsigned int addrBase,unsigned int addrOffset)
{
	int ans=0;
	ans=Xil_In32(addrBase+addrOffset);
	return ans;
}


#if 0
//reset
void GpioReset()
{
	xil_setreg32(GPIO_I2C_RESET_ADDR,0x4,0x0);
	xil_setreg32(GPIO_I2C_RESET_ADDR,0x0,0x2);
	//printf("gpio reset ok!\n");
}
#endif

void iic_write()
{
	unsigned int _data;
	memcpy((void*)&_data,&SendBuffer[0],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,0,_data);
	memcpy((void*)&_data,&SendBuffer[4],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,4,_data);
	memcpy((void*)&_data,&SendBuffer[8],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,8,_data);
	memcpy((void*)&_data,(void*)&SendBuffer[12],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,12,_data);
	memcpy((void*)&_data,(void*)&SendBuffer[16],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,16,_data);
	memcpy((void*)&_data,(void*)&SendBuffer[20],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,20,_data);
	memcpy((void*)&_data,(void*)&SendBuffer[24],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,24,_data);
	memcpy((void*)&_data,(void*)&SendBuffer[28],4);
	xil_setreg32(XPAR_AXI_BRAM_CTRL_I2C_S_AXI_BASEADDR,28,_data);
}

int IicSelfTest()
{
	unsigned int zynq_temp,temp_1848,v7_1_temp,v7_2_temp,v7_3_temp,v7_4_temp;

	zynq_temp=g_temp[0];
	temp_1848=g_temp[1];
	v7_1_temp=g_temp[2];
	v7_2_temp=g_temp[3];
	v7_3_temp=g_temp[4];
	v7_4_temp=g_temp[5];

	SendBuffer[0] = 0xa;
	SendBuffer[1] = 0x55;
	SendBuffer[2] = 0x4e;
	SendBuffer[3] = 0x2;
	SendBuffer[4] = srio_stat0;
	SendBuffer[5] = srio_stat1;
	SendBuffer[6] = 0x1;
	SendBuffer[7] = 0x1;
	SendBuffer[8] = 0x1;
	SendBuffer[9] = zynq_temp;
	SendBuffer[10] = temp_1848;
	SendBuffer[11] = v7_1_temp;
	SendBuffer[12] = v7_2_temp;
	SendBuffer[13] = v7_3_temp;
	SendBuffer[14] = v7_4_temp;

//	GpioReset();
	iic_write();
	return 1;
}


